package com.fauks.ee.freemarker;


import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用FreeMarker 模板代码生成
 */
public class Generator {

    private Configuration configuration;

    //初始化Configuration对象
    public void init() throws IOException {
        configuration = new Configuration(Configuration.getVersion());
        //获取并设置模板路径
        String path = this.getClass().getClassLoader().getResource("freemarker").getPath();
        configuration.setDirectoryForTemplateLoading(new File(path));
    }

    //代码生成
    public void process(String templateName, String savePath) throws Exception {
        //获取模板实例
        Template template = configuration.getTemplate(templateName);
        //参数
        Map<String, Object> params = new HashMap<>();
        params.put("name", "fauks");
        List<String> sList = new ArrayList<>();
        sList.add("a");
        sList.add("b");
        sList.add("c");
        params.put("sList", sList);
        params.put("isNew", true);
        params.put("age", 12);
        //生成代码的存放路径
        FileOutputStream fos = new FileOutputStream(savePath);
        OutputStreamWriter osWriter = new OutputStreamWriter(fos);
        template.process(params, osWriter);
    }

    public static void main(String[] args) {
        try {
            Generator generator = new Generator();
            generator.init();
            generator.process("test.ftl", "D:\\fm_gen\\a.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
